import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Form, Button, Table, Alert, Spinner, Modal, InputGroup, ListGroup } from 'react-bootstrap';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { runBacktest, searchBondSymbols } from '../services/api';
import moment from 'moment';

const BacktestTab = () => {
  // 回测参数状态
  const [startDate, setStartDate] = useState(new Date(new Date().setFullYear(new Date().getFullYear() - 1)));
  const [endDate, setEndDate] = useState(new Date());
  const [symbols, setSymbols] = useState('');  // 增加债券标的代码状态
  const [symbolsList, setSymbolsList] = useState([]);  // 解析后的标的代码列表
  
  // 债券搜索相关状态
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isSearching, setIsSearching] = useState(false);
  const [showSearchResults, setShowSearchResults] = useState(false);
  
  // 目标仓位状态
  const [positionDate, setPositionDate] = useState(new Date());
  const [positionWeights, setPositionWeights] = useState({});  // 使用对象存储所有标的权重
  const [positions, setPositions] = useState([]);
  const [deleteIndex, setDeleteIndex] = useState(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  
  // 回测结果状态
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [logs, setLogs] = useState([]);
  const [reportUrl, setReportUrl] = useState('');
  const [performanceMetrics, setPerformanceMetrics] = useState(null);
  const [showReportModal, setShowReportModal] = useState(false);

  // 处理债券搜索
  const handleSearchChange = async (e) => {
    const query = e.target.value;
    setSearchQuery(query);
    
    if (query.length >= 2) {
      setIsSearching(true);
      setShowSearchResults(true);
      try {
        const result = await searchBondSymbols(query);
        if (result.success) {
          setSearchResults(result.data);
        } else {
          console.error('搜索债券失败:', result.error);
          setSearchResults([]);
        }
      } catch (error) {
        console.error('搜索请求出错:', error);
        setSearchResults([]);
      } finally {
        setIsSearching(false);
      }
    } else {
      setSearchResults([]);
      setShowSearchResults(false);
    }
  };

  // 选择一个债券标的
  const selectBondSymbol = (bond) => {
    // 如果标的已经存在于列表中，不重复添加
    if (!symbolsList.includes(bond.symbol)) {
      const newSymbolsList = [...symbolsList, bond.symbol];
      setSymbolsList(newSymbolsList);
      
      // 更新显示的债券代码字符串
      setSymbols(newSymbolsList.join(', '));
      
      // 重新计算权重
      const equalWeight = newSymbolsList.length > 0 ? (1 / newSymbolsList.length).toFixed(4) : 0;
      const newWeights = {};
      newSymbolsList.forEach(s => {
        newWeights[s] = parseFloat(equalWeight);
      });
      setPositionWeights(newWeights);
    }
    
    // 关闭搜索结果显示并清空搜索框
    setShowSearchResults(false);
    setSearchQuery('');
  };

  // 渲染债券搜索下拉框
  const renderSearchResults = () => {
    if (!showSearchResults) return null;
    
    return (
      <div className="position-relative">
        <ListGroup 
          className="position-absolute w-100 shadow-sm" 
          style={{ zIndex: 1000, maxHeight: '300px', overflowY: 'auto' }}
        >
          {isSearching ? (
            <ListGroup.Item className="text-center">
              <Spinner animation="border" size="sm" /> 正在搜索...
            </ListGroup.Item>
          ) : searchResults.length > 0 ? (
            searchResults.map((bond, index) => (
              <ListGroup.Item 
                key={index} 
                action
                onClick={() => selectBondSymbol(bond)}
                className="d-flex justify-content-between align-items-center"
              >
                <div>
                  <strong>{bond.symbol}</strong> - {bond.name}
                </div>
                <div className="text-muted small">
                  票息: {bond.couponrate}% | 到期: {bond.maturitydate}
                </div>
              </ListGroup.Item>
            ))
          ) : (
            <ListGroup.Item>未找到匹配的债券</ListGroup.Item>
          )}
        </ListGroup>
      </div>
    );
  };

  // 当标的代码变更时，更新标的列表和权重
  useEffect(() => {
    if (symbols.trim()) {
      const newSymbolsList = symbols.split(',').map(s => s.trim()).filter(s => s);
      setSymbolsList(newSymbolsList);
      
      // 初始化权重，平均分配
      const equalWeight = newSymbolsList.length > 0 ? (1 / newSymbolsList.length).toFixed(4) : 0;
      const newWeights = {};
      newSymbolsList.forEach(s => {
        newWeights[s] = parseFloat(equalWeight);
      });
      
      setPositionWeights(newWeights);
    } else {
      setSymbolsList([]);
      setPositionWeights({});
    }
  }, [symbols]);

  // 更新单个标的权重
  const updateSymbolWeight = (symbol, value) => {
    // 允许输入小数点和数字
    // 检查输入是否是有效的数字格式（允许小数）
    const numericValue = value.replace(/[^0-9.]/g, '');
    
    // 确保只有一个小数点
    if ((numericValue.match(/\./g) || []).length > 1) {
      return; // 如果有多个小数点，不更新
    }
    
    setPositionWeights({
      ...positionWeights,
      [symbol]: value === '' ? '' : numericValue
    });
  };

  // 自动调整权重，确保总和为1
  const balanceWeights = () => {
    if (symbolsList.length === 0) return;
    
    // 将空字符串转换为0，保留合法的数值
    const cleanedWeights = { ...positionWeights };
    Object.keys(cleanedWeights).forEach(key => {
      cleanedWeights[key] = cleanedWeights[key] === '' ? 0 : parseFloat(cleanedWeights[key]);
    });
    
    const totalWeight = Object.values(cleanedWeights).reduce((sum, weight) => sum + weight, 0);
    
    if (totalWeight === 0) {
      // 如果总权重为0，平均分配
      const equalWeight = (1 / symbolsList.length).toFixed(4);
      const newWeights = {};
      symbolsList.forEach(s => {
        newWeights[s] = equalWeight;
      });
      setPositionWeights(newWeights);
    } else if (Math.abs(totalWeight - 1.0) > 0.01) {
      // 如果总权重不为1，按比例调整
      const factor = 1 / totalWeight;
      const newWeights = {};
      Object.entries(cleanedWeights).forEach(([symbol, weight]) => {
        newWeights[symbol] = (weight * factor).toFixed(4);
      });
      setPositionWeights(newWeights);
      setSuccess('已自动调整权重，总和为1.0');
    }
  };

  // 添加目标仓位
  const addPosition = () => {
    // 准备权重数据，确保所有值都是数字
    const numericWeights = {};
    let totalWeight = 0;
    
    for (const [symbol, weight] of Object.entries(positionWeights)) {
      const numValue = parseFloat(weight) || 0;
      numericWeights[symbol] = numValue;
      totalWeight += numValue;
    }
    
    // 验证权重和为1
    if (Math.abs(totalWeight - 1.0) > 0.01) {
      setError('所有债券权重之和必须等于1.0');
      return;
    }
    
    const formattedDate = moment(positionDate).format('YYYY-MM-DD');
    
    // 检查是否已存在该日期的仓位
    const existingIndex = positions.findIndex(p => p.date === formattedDate);
    
    if (existingIndex >= 0) {
      // 更新现有仓位
      const updatedPositions = [...positions];
      updatedPositions[existingIndex] = {
        date: formattedDate,
        weights: { ...numericWeights }
      };
      setPositions(updatedPositions);
      setError('');
      setSuccess(`已更新${formattedDate}的目标仓位`);
    } else {
      // 添加新仓位
      setPositions([
        ...positions,
        {
          date: formattedDate,
          weights: { ...numericWeights }
        }
      ]);
      setError('');
      setSuccess(`已添加${formattedDate}的目标仓位`);
    }
  };

  // 删除目标仓位
  const handleDeleteClick = (index) => {
    setDeleteIndex(index);
    setShowDeleteConfirm(true);
  };

  // 确认删除目标仓位
  const confirmDelete = () => {
    if (deleteIndex !== null) {
      const newPositions = positions.filter((_, index) => index !== deleteIndex);
      setPositions(newPositions);
      setDeleteIndex(null);
      setShowDeleteConfirm(false);
      setSuccess('已删除目标仓位');
    }
  };

  // 取消删除
  const cancelDelete = () => {
    setDeleteIndex(null);
    setShowDeleteConfirm(false);
  };

  // 执行回测
  const handleRunBacktest = async () => {
    if (positions.length === 0) {
      setError('请至少添加一个目标仓位');
      return;
    }

    if (!symbols.trim()) {
      setError('请输入回测标的代码');
      return;
    }

    setIsLoading(true);
    setError('');
    setSuccess('');
    setLogs([]);
    setReportUrl('');
    setPerformanceMetrics(null);

    try {
      const backtestParams = {
        start_date: moment(startDate).format('YYYY-MM-DD'),
        end_date: moment(endDate).format('YYYY-MM-DD'),
        symbols: symbols.trim(),  // 添加标的代码参数
        target_positions: positions
      };

      const response = await runBacktest(backtestParams);
      
      if (response.success) {
        setSuccess('回测执行成功！');
        console.log('回测响应数据:', response); // 添加调试日志
        console.log('回测日志数据:', response.data.logs); // 添加调试日志
        setLogs(response.data.logs || []);
        
        // 确保报告URL使用正确的域名和端口
        const reportUrl = response.data.report_url;
        // 如果是相对路径，添加完整的基础URL
        if (reportUrl && reportUrl.startsWith('/')) {
          setReportUrl(`http://localhost:5000${reportUrl}`);
        } else {
          setReportUrl(reportUrl);
        }
        
        setPerformanceMetrics(response.data.performance_metrics);
      } else {
        setError(response.error || '回测执行失败，未知错误');
      }
    } catch (err) {
      console.error('回测请求错误:', err); // 添加调试日志
      setError(err.error || '回测执行请求失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 当回测日期变更时，调整目标仓位日期
  const handleStartDateChange = (date) => {
    setStartDate(date);
    
    // 如果目标仓位日期早于新的开始日期，则调整到开始日期
    if (positionDate < date) {
      setPositionDate(date);
    }
  };
  
  const handleEndDateChange = (date) => {
    setEndDate(date);
    
    // 如果目标仓位日期晚于新的结束日期，则调整到结束日期
    if (positionDate > date) {
      setPositionDate(date);
    }
  };

  return (
    <div>
      {/* 回测参数卡片 */}
      <Row>
        <Col md={12}>
          <Card className="mb-4">
            <Card.Header>回测参数</Card.Header>
            <Card.Body>
              <Row>
                <Col md={6}>
                  <Form.Group className="mb-3">
                    <Form.Label>开始日期</Form.Label>
                    <DatePicker
                      selected={startDate}
                      onChange={handleStartDateChange}
                      selectsStart
                      startDate={startDate}
                      endDate={endDate}
                      className="form-control"
                      dateFormat="yyyy-MM-dd"
                    />
                  </Form.Group>
                </Col>
                <Col md={6}>
                  <Form.Group className="mb-3">
                    <Form.Label>结束日期</Form.Label>
                    <DatePicker
                      selected={endDate}
                      onChange={handleEndDateChange}
                      selectsEnd
                      startDate={startDate}
                      endDate={endDate}
                      minDate={startDate}
                      className="form-control"
                      dateFormat="yyyy-MM-dd"
                    />
                  </Form.Group>
                </Col>
              </Row>
              <Row>
                <Col md={12}>
                  <Form.Group className="mb-3">
                    <Form.Label>债券标的</Form.Label>
                    <div className="position-relative">
                      <InputGroup>
                        <Form.Control
                          type="text"
                          placeholder="搜索债券代码或名称..."
                          value={searchQuery}
                          onChange={handleSearchChange}
                          onFocus={() => searchQuery.length >= 2 && setShowSearchResults(true)}
                          onBlur={() => setTimeout(() => setShowSearchResults(false), 200)}
                        />
                        {isSearching && (
                          <InputGroup.Text>
                            <Spinner animation="border" size="sm" />
                          </InputGroup.Text>
                        )}
                      </InputGroup>
                      {renderSearchResults()}
                    </div>
                    <Form.Control
                      as="textarea"
                      rows={2}
                      placeholder="已选债券标的 (逗号分隔，如: 110033, 110034)"
                      value={symbols}
                      onChange={e => setSymbols(e.target.value)}
                      className="mt-2"
                    />
                  </Form.Group>
                </Col>
              </Row>
            </Card.Body>
          </Card>
        </Col>
      </Row>

      {/* 目标仓位设置卡片 */}
      <Row>
        <Col md={12}>
          <Card className="mb-4">
            <Card.Header>目标仓位设置</Card.Header>
            <Card.Body>
              {error && <Alert variant="danger">{error}</Alert>}
              {success && <Alert variant="success">{success}</Alert>}
              
              <Form>
                <Row>
                  <Col md={3}>
                    <Form.Group className="mb-3">
                      <Form.Label>日期</Form.Label>
                      <DatePicker
                        selected={positionDate}
                        onChange={date => setPositionDate(date)}
                        className="form-control"
                        dateFormat="yyyy-MM-dd"
                      />
                    </Form.Group>
                  </Col>
                  {symbolsList.map((symbol, index) => (
                    <Col md={3} key={index}>
                      <Form.Group className="mb-3">
                        <Form.Label>{symbol} 权重</Form.Label>
                        <Form.Control
                          type="text"
                          value={positionWeights[symbol] || ''}
                          onChange={e => updateSymbolWeight(symbol, e.target.value)}
                        />
                      </Form.Group>
                    </Col>
                  ))}
                </Row>
                <Row>
                  <Col md={12}>
                    <Button 
                      variant="primary" 
                      onClick={addPosition}
                      className="mb-3 me-2"
                    >
                      添加目标仓位
                    </Button>
                    <Button 
                      variant="secondary" 
                      onClick={balanceWeights}
                      className="mb-3"
                    >
                      自动调整权重
                    </Button>
                  </Col>
                </Row>
              </Form>

              {/* 目标仓位表格 */}
              <div className="table-responsive">
                <Table striped bordered hover className="position-table">
                  <thead>
                    <tr>
                      <th>日期</th>
                      {symbolsList.map((symbol, index) => (
                        <th key={index}>{symbol} 权重</th>
                      ))}
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {positions.length === 0 ? (
                      <tr>
                        <td colSpan={symbolsList.length + 2} className="text-center">尚无目标仓位，请添加</td>
                      </tr>
                    ) : (
                      positions.map((position, index) => (
                        <tr key={index}>
                          <td>{position.date}</td>
                          {symbolsList.map((symbol, symbolIndex) => (
                            <td key={symbolIndex}>{position.weights[symbol].toFixed(2)}</td>
                          ))}
                          <td>
                            <Button 
                              variant="danger" 
                              size="sm"
                              onClick={() => handleDeleteClick(index)}
                            >
                              删除
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </Table>
              </div>

              {/* 删除确认 */}
              {showDeleteConfirm && (
                <Alert variant="warning">
                  <p>确定要删除这个目标仓位吗？</p>
                  <Button variant="danger" onClick={confirmDelete} className="me-2">确定</Button>
                  <Button variant="secondary" onClick={cancelDelete}>取消</Button>
                </Alert>
              )}

              {/* 执行回测按钮 */}
              <Row className="mt-3">
                <Col md={12}>
                  <Button 
                    variant="success" 
                    onClick={handleRunBacktest}
                    className="btn-block"
                    disabled={isLoading}
                  >
                    {isLoading ? (
                      <>
                        <Spinner as="span" animation="border" size="sm" className="me-2" />
                        正在执行回测...
                      </>
                    ) : '执行回测'}
                  </Button>
                </Col>
              </Row>
            </Card.Body>
          </Card>
        </Col>
      </Row>
      
      {/* 回测结果和日志 */}
      {(logs.length > 0 || performanceMetrics) && (
        <Row>
          <Col md={12}>
            <Card className="mb-4">
              <Card.Header>回测结果</Card.Header>
              <Card.Body>
                {performanceMetrics && (
                  <div className="mb-4">
                    <h5>绩效指标</h5>
                    <Table bordered>
                      <tbody>
                        <tr>
                          <th>总收益率</th>
                          <td>{performanceMetrics.total_return ? (performanceMetrics.total_return * 100).toFixed(2) : "0.00"}%</td>
                          <th>年化收益率</th>
                          <td>{performanceMetrics.annual_return ? (performanceMetrics.annual_return * 100).toFixed(2) : "0.00"}%</td>
                        </tr>
                        <tr>
                          <th>年化波动率</th>
                          <td>{performanceMetrics.volatility ? (performanceMetrics.volatility * 100).toFixed(2) : "0.00"}%</td>
                          <th>夏普比率</th>
                          <td>{performanceMetrics.sharpe_ratio ? performanceMetrics.sharpe_ratio.toFixed(2) : "0.00"}</td>
                        </tr>
                        <tr>
                          <th>最大回撤</th>
                          <td>{performanceMetrics.max_drawdown ? (performanceMetrics.max_drawdown * 100).toFixed(2) : "0.00"}%</td>
                          <th>报告</th>
                          <td>
                            {reportUrl && (
                              <Button 
                                variant="primary" 
                                onClick={() => setShowReportModal(true)}
                              >
                                查看报告
                              </Button>
                            )}
                          </td>
                        </tr>
                      </tbody>
                    </Table>
                  </div>
                )}
                
                {/* 回测日志部分 */}
                {logs.length > 0 && (
                  <div className="mt-4">
                    <h5>回测日志</h5>
                    <div 
                      className="log-container p-3 bg-light" 
                      style={{ 
                        maxHeight: '300px', 
                        overflowY: 'auto',
                        borderRadius: '4px',
                        border: '1px solid #ced4da',
                        fontFamily: 'monospace',
                        fontSize: '14px',
                        whiteSpace: 'pre-wrap'
                      }}
                    >
                      {logs.map((log, index) => (
                        <div key={index} className="log-line">
                          {log}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </Card.Body>
            </Card>
          </Col>
        </Row>
      )}
      
      {/* 报告弹窗 */}
      <Modal 
        show={showReportModal} 
        onHide={() => setShowReportModal(false)} 
        size="xl"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>回测报告</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {reportUrl && (
            <iframe 
              src={reportUrl} 
              title="回测报告"
              className="report-iframe"
            />
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowReportModal(false)}>关闭</Button>
        </Modal.Footer>
      </Modal>
    </div>
  );
};

export default BacktestTab;
